package com.horoscope.astrology.zodiac.signs.free.service

import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.hardware.display.DisplayManager
import android.os.Build
import android.os.Bundle
import android.os.PowerManager
import android.view.Display
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import com.horoscope.astrology.zodiac.signs.free.AppSettingManager
import com.horoscope.astrology.zodiac.signs.free.MmoApplication
import com.horoscope.astrology.zodiac.signs.free.R
import com.horoscope.astrology.zodiac.signs.free.activity.ArticleDetailActivity
import com.horoscope.astrology.zodiac.signs.free.activity.QuizStartActivity
import com.horoscope.astrology.zodiac.signs.free.activity.SplashActivity
import com.horoscope.astrology.zodiac.signs.free.utils.SysUtils


/**
 * Firebase 的推送（此处的设置要结合后台，有些配置是后台去做的）
 * 它会在接收到推送的时候被回调。（app在前台的状态）
 * 注意这里的方法都是在 WorkerThread 线程中完成的，所以要额外注意操作 UI 的情况
 * am: 只是为了增加app打开次数
 * pm: 实际文章的推送
 * quiz: 提高quiz利用率
 * */
class MyFirebaseMessagingService : FirebaseMessagingService() {

    val context = MmoApplication.getInstance()

    // 它主要用于处理接收 App 正在运行的时候，接收到的推送
    // app处于前台可见时，会调用此方法，在后台时需要通过click_action来配置隐式启动通过bundle来获取data数据
    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        super.onMessageReceived(remoteMessage)

        val userBean = AppSettingManager.readObject("user_info")
        if (remoteMessage.data.isNotEmpty()) {
            val type = remoteMessage.data["type"]
            val title = remoteMessage.notification!!.title
            val content = remoteMessage.notification!!.body

            // 读一下本地的用户信息
            when (type) {
                "1" -> {
                    createIntent(null, title, "Hi, ${userBean?.name}, ${getTitle()}", type)
                }
                "2" -> {
                    // Article http://asopp.com/app/horoscope/push_news/1060508739/
                    createIntent(remoteMessage.data["url"], title, content, type)
                }
                "3" -> {
                    // Quiz http://asopp.com/app/horoscope/quizid/1366278071/
                    createIntent(remoteMessage.data["url"], title, content, type)
                }

            }
        } else {
            createIntent(null, "Horoscope", "Hi, ${userBean?.name}, ${getTitle()}", "1")
        }
    }

    // am_Push随机取一个title使用
    private fun getTitle(): String {
        val strArray = context.resources.getStringArray(R.array.push_am_body)
        val index = (0..14).random()
        return if (index < strArray.size) {
            strArray[index]
        } else {
            strArray[0]
        }

    }

    // 监控令牌的生成，每当生成新令牌时，都会触发 onNewToken 回调函数。
    override fun onNewToken(token: String) {
        super.onNewToken(token)
    }

    private fun createIntent(url: String?, title: String?, text: String?, type: String) {
        val bundle = Bundle()
        //判断应用是否是启动状态
        val mainIntent = when (type) {
            "1" -> Intent(context, SplashActivity::class.java)
            "2" -> Intent(context, ArticleDetailActivity::class.java)
            "3" -> Intent(context, QuizStartActivity::class.java)
            else -> Intent(context, SplashActivity::class.java)
        }
        bundle.putString("type", type)
        if (url != null && type == "2") {
            mainIntent.putExtra("article_url", url)
        } else {
            mainIntent.putExtra("quiz_url", url)
        }
        mainIntent.putExtra("push", true)
        mainIntent.putExtra("bundle", bundle)
        createNotification(mainIntent, text, title)
    }

    private fun createNotification(mainIntent: Intent, text: String?, title: String?) {
        val mainPaddingIntent = PendingIntent.getActivities(
            context,
            0, arrayOf(mainIntent), PendingIntent.FLAG_UPDATE_CURRENT
        )
        val builder = NotificationCompat
            .Builder(context, SysUtils.createNotificationChannel(context, isScreenOn()))
            .setColor(ContextCompat.getColor(context, R.color.purple_5))
            .setSmallIcon(R.mipmap.icon_alpha_push)
            .setLargeIcon(
                BitmapFactory.decodeResource(
                    context.resources,
                    R.mipmap.ic_launcher_new
                )
            )
            .setStyle(NotificationCompat.BigTextStyle().bigText(text))
            .setAutoCancel(true)
            .setContentTitle(title)
            .setContentText(text)
            .setContentIntent(mainPaddingIntent)
            .setDefaults(Notification.DEFAULT_ALL)

        val notifyManager =
            context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notifyManager.notify(((Math.random() * 9 + 1) * 100000).toInt(), builder.build())
    }

    @SuppressLint("ObsoleteSdkInt")
    private fun isScreenOn(): Boolean {
        if (Build.VERSION.SDK_INT >= 20) {
            val dm = context.getSystemService(Context.DISPLAY_SERVICE) as DisplayManager
            val displays = dm.displays
            for (display in displays) {
                if (display.state == Display.STATE_ON || display.state == Display.STATE_UNKNOWN)
                    return true
            }
        }

        val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager
        if (powerManager.isInteractive) {
            return true
        }
        return false
    }


}